using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using MBLocale;

/// <summary>
/// Summary description for LoadEditPage
/// </summary>
public class LoadEditPage
{
    string strErrMessage = "";
    //ArrayList currencyCode_Rate = new ArrayList();
    public LoadEditPage()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    DynamicDisplayI DDI = new DynamicDisplayI();

    //private void loadCurrencySettings()//ssks
    //{
    //    //ArrayList currencyCode_Rate = new ArrayList();
    //    ArrayList cols = new ArrayList();
    //    cols.Add("c_rate"); cols.Add("c_code");
    //    currencyCode_Rate = DDI.getUserSetting("sy_usr", "currency_id", "sy_currency", cols, "c_code");
    //    currencyCode_Rate.Add(DDI.getCorporateCurrency());
    //    //return currencyCode_Rate;
    //}
    public bool LoadEditData(DataSet dsePageInfo, HtmlForm frmObj, string strKeys)
    {
        bool blnStatus = true;
        try
        {
            DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
            DataTable dtaPage = dsePageInfo.Tables["Page"];
            DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
            DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];
            string strPageId = "";
            string sAF_ROW_ID = "";
            string strPageKeyValues = "";
            string[] strPageKeys = strKeys.Split(GlobalValues.PageSetKeyChar);
            string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

//            loadCurrencySettings();//ssks

            for (int i = 0; i < dtaPage.Rows.Count; i++)
            {
                strPageId = dtaPage.Rows[i]["page_id"].ToString();
                sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();

                //if (i < strPageKeys.Length)
                //{
                strPageKeyValues = strPageKeys[0];
                //}
                //else
                //{
                    //strPageKeyValues = GetPageKey(dtaPageKeys, dtaPage, i, strKeys);
                //}
                DataRow[] drr = null;

                if (dtaPageKeys.Columns.Count != 0)
                    drr = dtaPageKeys.Select("af_row_id='" + sAF_ROW_ID + "'"); //af_row_id because pagekeys af_row_id is populated with the relevant page's af_row_id
                LoadDataPage(dtaPage.Select("page_id='" + strPageId.Replace("'", "''") + "'"), drr/*, "page_key_seq")*/,
                    dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'"), frmObj, strPageKeyValues, dtaPage, dtaPageKeys, i, sUTC_Offset);
            }
        }
        catch (Exception ex)
        {
            blnStatus = false;
            strErrMessage = ex.Message.ToString();
            LogWriter.WriteLog("Error in edit operation : " + ex.ToString());
        }
        return blnStatus;
    }

    private void AddDataTableForAuditLog(ref DataTable dtData)
    {
        if (dtData != null)
        {
            if (dtData.Rows.Count > 0)
            {
                GlobalValues.dsAudit.Tables.Clear();
                GlobalValues.dsAudit.Tables.Add(dtData.Copy());
            }
        }
    }

    private bool LoadDataPage(DataRow[] droPage, DataRow[] droPageKeys, DataRow[] droPageCtrl, HtmlForm frmObj,
        string strPageKeys, DataTable dtaPage, DataTable dtaPageKeys, int intPageSeq, string sUTC_Offset)
    {
        bool blnStatus = true;
        //build the select sql
        //  build the where condition
        // Load the data
        // fill the values with the corresponding cells
        string strSql = GetPageSelectSql(droPage, droPageKeys, droPageCtrl, strPageKeys);
        HDDatabase HDD = new HDDatabase();
        DataTable dtaData = HDD.GetDataTable(strSql, droPage[0]["page_id"].ToString());
        //added by Sampath on 10-Nov-2011 for Decoding
        //CommonFunctions.decodeData(dtaData);

        AddDataTableForAuditLog(ref dtaData);
        showDefaultValues(ref dtaData, frmObj, sUTC_Offset);//implemented by sanal on 08 April 2008
        FillDataValues(droPage, droPageKeys, droPageCtrl, frmObj, dtaData, dtaPage, dtaPageKeys, intPageSeq, sUTC_Offset);
        return blnStatus;
    }
    private string getUserName(string rowid)
    {
        HDDatabase hdd = new HDDatabase();
        DataTable dt = new DataTable();
        string ret="";
        try
        {
            string userDisplayField = hdd.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
            userDisplayField = userDisplayField.Trim().Length == 0 ? "user_id" : userDisplayField;
            dt = hdd.GetDataTable("select " + userDisplayField + " from sy_usr where af_row_id='" + rowid + "'");
            if (dt!=null)
                if (dt.Rows.Count>0)
                    ret = dt.Rows[0][0].ToString();
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in getUserName : " + e.ToString());
        }
        finally
        {
            hdd = null;
            dt = null;
        }
        return ret;
    }
    private void showDefaultValues(ref DataTable dtData, HtmlForm frmObj, string sUTC_Offset)//implemented by sanal on 08 April 2008
    {
        if (HttpContext.Current.Request.QueryString["CPY"] != null)
        {
            if (HttpContext.Current.Request.QueryString["CPY"] == "0")
            {
                return;
            }
        }
        if (dtData == null) return;
        if (dtData.Rows.Count < 1) return;
        if (!dtData.Columns.Contains("created_by")) return;
        if (!dtData.Columns.Contains("modified_at")) return;
        try
        {
            HtmlTable ht = new HtmlTable();
            HtmlTableRow htr = new HtmlTableRow();
            
            //HDDatabase hdd = new HDDatabase();
            //string userDisplayField = hdd.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
            //userDisplayField = userDisplayField.Trim().Length==0 ? "user_id" : userDisplayField;
            //string userName = hdd.GetColumnValue("sy_usr", userDisplayField, "af_row_id='" + dtData.Rows[0]["created_by"].ToString() + "'");
            string userName = getUserName(dtData.Rows[0]["created_by"].ToString()); //hdd.GetColumnValue("sy_usr", userDisplayField, "af_row_id='" + dtData.Rows[0]["created_by"].ToString() + "'");
            //hdd = null;
            

            HtmlTableCell htc = new HtmlTableCell();
            if (userName.Trim().Length>0)
            {
                //htc.Controls.Add(new LiteralControl("<b>Owner:</b>&nbsp;" + userName));
                // Added by srivatsan on June 15 2009 for owner id field
                htc.Controls.Add(new LiteralControl("<b>Created By:</b>&nbsp;" + userName));
                htc.Width = "50%";
                htr.Cells.Add(htc);
                //ht.Rows.Add(htr);
            }
            userName = null;

            htc = new HtmlTableCell();
            //DateTime dt = DateTime.Parse(dtData.Rows[0]["modified_at"].ToString());
            //string dat = DDI.getUsersDT(dtData.Rows[0]["modified_at"].ToString(), sUTC_Offset);
            Localization ll = new Localization();
            //htc.Controls.Add(new LiteralControl("<b>Last updated at:</b>&nbsp;" + dt.ToLocalTime().ToString("dd-MMM-yyyy hh:mm:ss tt")));
            htc.Controls.Add(new LiteralControl("<b>Last updated at:</b>&nbsp;" + ll.getDateTime4TimeZone(dtData.Rows[0]["modified_at"].ToString(),sUTC_Offset,false,true)));
            ll = null;
            htc.Width = "50%";
            htc.Align = "center";
            htr.Cells.Add(htc);
            
            ht.Rows.Add(htr);
            htr.Attributes.Add("Class", "Dynamic_HtmlTableCell");     

            HtmlTableCell htcObj = (HtmlTableCell) DDI.FindControl(frmObj.Controls, "tdcDefaultFields");
            ht.Width = "100%";
            ht.Border = 0;
            ht.CellPadding = 0;
            ht.CellSpacing = 0;
            ht.EnableViewState = false;
            htcObj.Controls.Add(ht);
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in showDefaultValues function. Error: " + e.Message);
        }
    }
    private string GetPageSelectSql(DataRow[] droPage, DataRow[] droPageKeys, DataRow[] droPageCtrl, string strPageKeys)
    {
        string strSql = "";
        string strPageTblName = droPage[0]["page_table_name"].ToString();
        string[] strKeys = strPageKeys.Split('~');
        string strPgKey = "";
        string strWhCond = "";
        string strOrderBy = "";
        for (int i = 0; i < strKeys.Length; i++)
        {
            //if (droPageKeys != null)
            //{
            //    strPgKey = droPageKeys[i]["attrib_id"].ToString();
            //    if (strWhCond != "")
            //    {
            //        strWhCond += " and ";
            //    }
            //}
            //else
            strPgKey = "af_row_id";
            //if (droPageKeys.Length > 0) // Added by srivatsan for testing
            //    strPgKey = droPageKeys[0]["attrib_id"].ToString();
            //string sTemp = getMasterDetailKey(strPageTblName);
            //if (sTemp != "") strPgKey = sTemp;
            strWhCond += "[" + strPageTblName + "].[" + strPgKey + "] = '" + strKeys[i].Replace("'", "''") + "' ";
        }
        for (int i = 0; i < droPageCtrl.Length; i++)
        {
            if (Convert.ToBoolean(droPageCtrl[i]["is_seq_control"].ToString() == "" ? "false" : droPageCtrl[i]["is_seq_control"].ToString()))
            {
                if (strOrderBy != "")
                {
                    strOrderBy += ", ";
                }
                strOrderBy += droPageCtrl[i]["control_attrib_id"].ToString().Replace("'", "''");
            }
        }
        strSql = "select * from [" + strPageTblName + "] where " + strWhCond;
        if (strOrderBy != "")
        {
            strSql += " order by [" + strOrderBy + "]";
        }
        return strSql;
    }

    private bool FillDataValues(DataRow[] droPage, DataRow[] droPageKeys, DataRow[] droPageCtrl, HtmlForm frmObj,
        DataTable dtaData, DataTable dtaPage, DataTable dtaPageKeys, int intPageSeq, string sUTC_Offset)
    {
        //HDDatabase HDD = new HDDatabase();
        //bool bEdit = Convert.ToBoolean(HDD.getObjectRightsForUser(droPage[0]["object_id"].ToString())["edit"]);
        bool blnStatus = true;
        string strCtrlId = "";
        string strCtrlType = "";
        string strCtrlColumn = "";
        string strDataType = "";
        string strBindRowID = "";
        bool blnMultipleRecsPage = Convert.ToBoolean(droPage[0]["multiple_recs_page"].ToString());
        string strPageId = droPage[0]["page_id"].ToString();
        HtmlTable htaMain = new HtmlTable();
        //if (frmObj.FindControl("tblDynamicMain") != null)
        //{
        //    htaMain = (HtmlTable)frmObj.FindControl("tblDynamicMain");
        //}
        if (DDI.FindControl(frmObj.Controls, "tblDynamicMain") != null)
        {
            htaMain = (HtmlTable)DDI.FindControl(frmObj.Controls, "tblDynamicMain");

            if (dtaData.Rows.Count > 1)
            {
                DDI.LoadPageMember(dtaPage, frmObj, htaMain, droPageCtrl, dtaPageKeys, intPageSeq, 1, dtaData.Rows.Count,null,null);
            }
            DataRow[] drTemp = null;
            //if (dtaData.Columns.Contains("attrib_seq"))
            //    drTemp = dtaData.Select("", "attrib_seq asc");
            //else
                drTemp = dtaData.Select("");
            for (int i = 0; i < drTemp.Length; i++)//for (int i = 0; i < dtaData.Rows.Count; i++)
            {
                for (int j = 0; j < droPageCtrl.Length; j++)
                {
                    /////strCtrlId = droPageCtrl[j]["control_id"].ToString();
                    /////j
                    strCtrlId = droPageCtrl[j]["control_attrib_id"].ToString();
                    strCtrlType = droPageCtrl[j]["control_html"].ToString();
                    strCtrlColumn = droPageCtrl[j]["control_attrib_id"].ToString();
                    strDataType = droPageCtrl[j]["control_attrib_type"].ToString();
                    strBindRowID = droPageCtrl[j]["control_bind_id"].ToString();
                    strCtrlId = strPageId + "_" + strCtrlId;
                    if (blnMultipleRecsPage)
                    {
                        strCtrlId += "_" + (i + 1).ToString();
                    }
                    //if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                    //    if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                    //        strCtrlType = "";

                    //if (bEdit == false) strCtrlType = "";
                    if (drTemp[i][strCtrlColumn] != System.DBNull.Value)
                        AssignValue(strCtrlId, strCtrlType, drTemp[i][strCtrlColumn].ToString(), strDataType, frmObj,droPageCtrl[j]["control_visible"].ToString(), sUTC_Offset,strBindRowID,dtaPageKeys,drTemp[i]["owner_id"].ToString());
                }
            }
        }
        return blnStatus;
    }

    private bool AssignValue(string strCtrlId, string strCtrlType, string strCtrlValue, string strDataType, HtmlForm frmObj, string control_visible, string sUTC_Offset, string strBindRowID, DataTable dtaPageKeys, string recordOwner)
    {
        bool blnStatus = true;
        string strActualValue = "";
        Control ctrlObj = DDI.FindControl(frmObj.Controls, strCtrlId);//frmObj.FindControl(strCtrlId);        
        if (ctrlObj != null)
        {
            switch (strDataType.ToUpper())
            {
                case GlobalValues.Number:
                    break;
                case GlobalValues.Date:
                    if (strCtrlValue != "")
                    {
                        strActualValue = strCtrlValue;
                        strCtrlValue = (Convert.ToDateTime(strCtrlValue)).ToShortDateString();
                        strCtrlValue = DateTime.Parse(strCtrlValue).ToString("dd-MMM-yyyy");

                    }
                    break;
                case GlobalValues.DateTime:
                    if (strCtrlValue != "")
                    {
                        strActualValue = strCtrlValue;
                        if (!strCtrlId.EndsWith("_created_at"))
                            strCtrlValue = DDI.getUsersDT(strCtrlValue, sUTC_Offset);
                        /*if (strCtrlValue != "")
                        {
                            strCtrlValue = (Convert.ToDateTime(strCtrlValue)).ToShortDateString() + " " + (Convert.ToDateTime(strCtrlValue)).ToShortTimeString();
                        }*/
                    }
                    break;
                case GlobalValues.Currency:
                    //strCtrlValue = DDI.manageCurrency(strCtrlValue, currencyCode_Rate);
                    break;
                default:
                    break;
            }
            //if (strCtrlId.IndexOf("af_row_id") > -1)//ssks
            if (!Convert.ToBoolean(control_visible == "" ? "false" : control_visible))
            {
                HiddenField txtObj = (HiddenField)ctrlObj;
                txtObj.Value = strCtrlValue;
                return true;
            }
            switch (strCtrlType.ToUpper())
            {
                case "AN":
                    if (HttpContext.Current.Request.QueryString["CPY"] == null)
                    {
                        TextBox txtAN = (TextBox)ctrlObj;
                        txtAN.Text = strCtrlValue;
                    }
                    break;
                case "TB":  // modified by srivatsan
                case "EM":
                    if (strBindRowID != "")
                    {
                        string strbindtext = "";
                        
                        //if (!frmObj.Page.IsPostBack)
                        //{
                            HDDatabase Hdd = new HDDatabase();
                            BindControl BC = new BindControl();
                            TextBox txtobj = (TextBox)DDI.FindControl(frmObj.Controls, "txt_" + strCtrlId);
                            HiddenField hfobj = (HiddenField)DDI.FindControl(frmObj.Controls, strCtrlId);
                            string sql1 = BC.GetBindSql(strBindRowID,false);
                            DataSet ds = new DataSet();
                            ds = Hdd.GetDataset(sql1);
                            BC.HandleLocalizedBindText(ds.Tables[0], strBindRowID); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
                            //CommonFunctions.decodeData(ds);
                            if (ds != null)
                            {
                                if (ds.Tables.Count > 0)
                                {
                                    if (ds.Tables[0].Rows.Count > 0)
                                    {
                                        DataRow[] drr = ds.Tables[0].Select("val='" + strCtrlValue.Replace("'","''") + "'");
                                        if(drr.Length>0)
                                        {
                                            strbindtext = drr[0]["fld"].ToString();
                                        }
                                            else
                                            {
                                                strbindtext = "";
                                            }
                                        

                                        
                                    }
                                }
                            }
                        //}

                        if (!frmObj.Page.IsPostBack)
                        {
                            hfobj.Value = strCtrlValue;
                            txtobj.Text = strbindtext;
                        }
                        if (HttpContext.Current.Request.QueryString["PK"] != null) // Added for Master detail pages
                        {
                            if (HttpContext.Current.Request.QueryString["MK"] != null)
                            {
                                hfobj.Value = strCtrlValue;
                                txtobj.Text = strbindtext;
                            }
                        }

                        SetDefaultValueForOwnerID(ref txtobj, ref hfobj, strCtrlId);

                    }
                    else
                    {
                        if (ctrlObj is HiddenField)
                        {
                            //if(HttpContext.Current.Request.QueryString["MK"]!=null)
                            //{
                            TextBox txtobj = (TextBox)DDI.FindControl(frmObj.Controls, "txt_" + strCtrlId);
                            HiddenField hfobj = (HiddenField)DDI.FindControl(frmObj.Controls, strCtrlId);

                            string strTableName = "";
                            string bindfield = "";
                            string sMSFieldDataType = ""; // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
                            if (dtaPageKeys != null)
                            {
                                if (dtaPageKeys.Rows.Count > 0)
                                {
                                    HDDatabase HDD =new HDDatabase();
                                    string masterobj = dtaPageKeys.Rows[0]["master_obj"].ToString();
                                    bindfield = dtaPageKeys.Rows[0]["display_att"].ToString();
                                    strTableName = HDD.GetColumnValue("sy_obj", "object_table", "object_id='" + masterobj + "'");
                                    sMSFieldDataType = HDD.GetColumnValue("select attrib_data_type from sy_obj_att where object_id = (select af_row_id from sy_obj where object_id = '" + masterobj + "') and attrib_id = '" + bindfield + "';");
                                    HDD = null;
                                }
                            }
                            if (strTableName != "")
                            {
                                MasterDetail MD = new MasterDetail();
                                DataTable dtaMaster = MD.GetMasterDataFromAfrowid(strTableName,strCtrlValue);
                                if (dtaMaster != null)
                                {
                                    if (dtaMaster.Rows.Count > 0)
                                    {
                                        if (hfobj.Value != "")
                                        {
                                            DataRow[] drrselect = dtaMaster.Select("af_row_id = '" + hfobj.Value + "'");
                                            if (drrselect.Length > 0)
                                            {
                                                txtobj.Text = drrselect[0][bindfield].ToString();
                                                hfobj.Value = drrselect[0]["af_row_id"].ToString();
                                            }
                                            else
                                            {
                                                txtobj.Text = dtaMaster.Rows[0][bindfield].ToString();
                                                hfobj.Value = strCtrlValue;
                                            }
                                        }
                                        else
                                        {
                                            txtobj.Text = dtaMaster.Rows[0][bindfield].ToString();
                                            hfobj.Value = strCtrlValue;
                                        }
                                        #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                                        switch (sMSFieldDataType.ToLower())
                                        {
                                            case "da":
                                                //setAjaxDate(txtobj.ID, strCtrlValue, ref DDI, ref frmObj);
                                                break;
                                            case "cu":
                                            case "dc":
                                            case "fl":
                                                if (strCtrlValue != "")
                                                    txtobj.Text = MBLocalization.getLocalizedDecimal(HttpContext.Current.Session["userlocale"].ToString(), Convert.ToDouble(txtobj.Text));
                                                break;
                                            case "nu":
                                            case "an":
                                                if (strCtrlValue != "")
                                                    txtobj.Text = MBLocalization.getLocalizedInteger(HttpContext.Current.Session["userlocale"].ToString(), Convert.ToInt32(txtobj.Text));
                                                break;
                                        }
                                        #endregion
                                    }
                                }
                            
                            }
                           // }
                        }
                        else
                        {
                            TextBox txtObj = (TextBox)ctrlObj;
                            txtObj.Text = strCtrlValue;
                            #region Old Code commented by 'Imran Gani' on 28-Feb-2014, to avoid 'if' statement and to use switch case.
                            //Localization ll = new Localization();
                            //if (strDataType == "DA")
                            //{
                            //    setAjaxDate(txtObj.ID, strCtrlValue, ref DDI, ref frmObj);
                            //}
                            //else if (strDataType == "CU")
                            //{
                            //    if (strCtrlValue != "")
                            //            txtObj.Text = ll.getUserCurrency(Convert.ToDouble(strCtrlValue));
                            //}
                            //ll = null;
                            #endregion

                            #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                            switch (strDataType.ToLower())
                            {
                                case "da":
                                    setAjaxDate(txtObj.ID, strCtrlValue, ref DDI, ref frmObj);
                                    break;
                                case "cu":
                                case "dc":
                                case "fl":
                                    if (strCtrlValue != "")
                                        txtObj.Text = MBLocalization.getLocalizedDecimal(HttpContext.Current.Session["userlocale"].ToString(), Convert.ToDouble(strCtrlValue));
                                    break;
                                case "nu":
                                case "an":
                                    if (strCtrlValue != "")
                                        txtObj.Text = MBLocalization.getLocalizedInteger(HttpContext.Current.Session["userlocale"].ToString(), Convert.ToInt32(strCtrlValue));
                                    break;
                            }
                            #endregion
                        }
                    }

                    //TextBox txtObj = (TextBox)ctrlObj;
                    //txtObj.Text = strCtrlValue;
                    //if (strDataType == "DA")
                    //{
                    //    setAjaxDate(txtObj.ID, strCtrlValue, ref DDI, ref frmObj);
                    //}
                    //else if (strDataType == "CU")
                    //{
                    //    if (strCtrlValue != "")
                    //    {
                    //        Localization ll = new Localization();
                    //        try
                    //        {
                    //            txtObj.Text = ll.getUserCurrency(Convert.ToDouble(strCtrlValue));
                    //        }
                    //        catch (Exception ee) { }
                    //        ll = null;
                    //    }
                    //}
                    break;
                case "TA":
                    TextBox txtTAObj;
                    txtTAObj = (TextBox)ctrlObj;
                    txtTAObj.Text = strCtrlValue;
                    break;
                case "DD":
                case "DDE":
                    if (ctrlObj is HiddenField)
                    {
                        //if (HttpContext.Current.Request.QueryString["MK"] != null)
                        //{
                            TextBox txtobj = (TextBox)DDI.FindControl(frmObj.Controls, "txt_" + strCtrlId);
                            HiddenField hfobj = (HiddenField)DDI.FindControl(frmObj.Controls, strCtrlId);

                            string strTableName = "";
                            string bindfield = "";
                            if (dtaPageKeys != null)
                            {
                                if (dtaPageKeys.Rows.Count > 0)
                                {
                                    HDDatabase HDD = new HDDatabase();
                                    string masterobj = dtaPageKeys.Rows[0]["master_obj"].ToString();
                                    bindfield = dtaPageKeys.Rows[0]["display_att"].ToString();
                                    strTableName = HDD.GetColumnValue("sy_obj", "object_table", "object_id='" + masterobj + "'");
                                    HDD = null;
                                }
                            }
                            if (strTableName != "")
                            {

                                MasterDetail MD = new MasterDetail();

                                DataTable dtaMaster = MD.GetMasterDataFromAfrowid(strTableName, strCtrlValue);

                                if (dtaMaster != null)
                                {
                                    if (dtaMaster.Rows.Count > 0)
                                    {
                                        if (hfobj.Value != "")
                                        {
                                            DataRow[] drrselect = dtaMaster.Select("af_row_id = '" + hfobj.Value + "'");
                                            if (drrselect.Length > 0)
                                            {
                                                txtobj.Text = drrselect[0][bindfield].ToString();
                                                hfobj.Value = drrselect[0]["af_row_id"].ToString();

                                            }
                                            else
                                            {
                                                txtobj.Text = dtaMaster.Rows[0][bindfield].ToString();
                                                hfobj.Value = strCtrlValue;
                                            }
                                        }
                                        else
                                        {
                                            txtobj.Text = dtaMaster.Rows[0][bindfield].ToString();
                                            hfobj.Value = strCtrlValue;
                                        }
                                    }
                                }

                            }
                        //}
                    }
                    else
                    {
                        DropDownList ddlObj = (DropDownList)ctrlObj;
                        if (strCtrlType.ToUpper() == "DDE") // Added by srivatsan for DDE Changes
                        {
                            BindControl BC = new BindControl();
                            HDDatabase HDD = new HDDatabase();
                            //DropDownList DDLObj = new DropDownList();
                            if (strBindRowID != "")
                            {
                                string sql = BC.GetBindSql(strBindRowID);
                                if (sql.Trim() != "")
                                {
                                    DataTable dt = HDD.GetDataTable(sql);
                                    if(dt!=null)
                                    {
                                        //SetValueForDDE(ref ddlObj, strBindRowID, null, strCtrlValue);
                                        DataRow[] drr = dt.Select("Val='"+strCtrlValue+"'");
                                        if (drr.Length > 0)
                                        {
                                            ListItem Item = new ListItem(drr[0]["Fld"].ToString(), drr[0]["Val"].ToString());
                                            if(!ddlObj.Items.Contains(Item))
                                                ddlObj.Items.Insert(0, Item);

                                            ddlObj.SelectedValue = Item.Value;
                                        }
                                    }
                                }
                            }

                        }
                        else
                        {
                            //ddlObj.Text = strCtrlValue;
                            AssignValueForDD(ref ddlObj, strDataType, strActualValue, strCtrlValue);
                        }
                    }
                    //SetDefaultValueForOwnerID(ref ddlObj, strCtrlId);
                    break;
                case "DA":
                    TextBox txtDAObj = (TextBox)ctrlObj;
                    //C1WebDateEdit txtDAObj = (C1WebDateEdit)ctrlObj;
                    txtDAObj.Text = strCtrlValue;
                    break;
                case "CB":
                    CheckBox cbDAObj = (CheckBox)ctrlObj;
                    //cbDAObj.Text = strCtrlValue;
                    if (strCtrlValue == "")
                        cbDAObj.Checked = false;
                    else
                        cbDAObj.Checked = Convert.ToBoolean(strCtrlValue);
                    break;
                case "DT":
                    TextBox txtDTObj = (TextBox)ctrlObj;
                    //C1WebDateEdit txtDTObj = (C1WebDateEdit)ctrlObj;
                    txtDTObj.Text = strCtrlValue;
                    break;
                case "PW":
                    TextBox txtPWObj = (TextBox)ctrlObj;
                    bool showValue = changeTextBoxPropertiesBasedOnSettings(ref txtPWObj, recordOwner);
                    string orgValue = security.decrypt(strCtrlValue);
                    if (showValue)
                    {
                        HiddenField hfobj = (HiddenField)DDI.FindControl(frmObj.Controls, "pwd_org_" + strCtrlId);
                        if (hfobj != null)
                            hfobj.Value = orgValue;
                    }
                    txtPWObj.Text = orgValue;
                    break;
                case "ENC": // Added by 'Imran Gani' on 10-Jul-2014, to handle encryption fields.
                    TextBox txtENCObj = (TextBox)ctrlObj;
                    txtENCObj.Text = security.decrypt(strCtrlValue);
                    break;
                case "DL": // Added by 'Imran Gani' on 26-Dec-2013, for droplist support.
                    if (ctrlObj is HiddenField)
                    {
                        TextBox txtobj = (TextBox)DDI.FindControl(frmObj.Controls, "txt_" + strCtrlId);
                        HiddenField hfobj = (HiddenField)DDI.FindControl(frmObj.Controls, strCtrlId);

                        string strTableName = "";
                        string bindfield = "";
                        if (dtaPageKeys != null)
                        {
                            if (dtaPageKeys.Rows.Count > 0)
                            {
                                HDDatabase HDD = new HDDatabase();
                                string masterobj = dtaPageKeys.Rows[0]["master_obj"].ToString();
                                bindfield = dtaPageKeys.Rows[0]["display_att"].ToString();
                                strTableName = HDD.GetColumnValue("sy_obj", "object_table", "object_id='" + masterobj + "'");
                                HDD = null;
                            }
                        }
                        if (strTableName != "")
                        {
                            MasterDetail MD = new MasterDetail();
                            DataTable dtaMaster = MD.GetMasterDataFromAfrowid(strTableName, strCtrlValue);
                            if (dtaMaster != null)
                            {
                                if (dtaMaster.Rows.Count > 0)
                                {
                                    if (hfobj.Value != "")
                                    {
                                        DataRow[] drrselect = dtaMaster.Select("af_row_id = '" + hfobj.Value + "'");
                                        if (drrselect.Length > 0)
                                        {
                                            txtobj.Text = drrselect[0][bindfield].ToString();
                                            hfobj.Value = drrselect[0]["af_row_id"].ToString();
                                        }
                                        else
                                        {
                                            txtobj.Text = dtaMaster.Rows[0][bindfield].ToString();
                                            hfobj.Value = strCtrlValue;
                                        }
                                    }
                                    else
                                    {
                                        txtobj.Text = dtaMaster.Rows[0][bindfield].ToString();
                                        hfobj.Value = strCtrlValue;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        DropDownList ddlObj = (DropDownList)ctrlObj;
                        //AssignValueForDD(ref ddlObj, strDataType, strActualValue, strCtrlValue);
                        if (ddlObj.Items.FindByValue(strCtrlValue) == null)
                            ddlObj.Items.Add(new ListItem(strCtrlValue, strCtrlValue));
                        ddlObj.Items.FindByValue(strCtrlValue).Selected = true;
                        //ddlObj.Text = strCtrlValue;
                    }
                    break;
                default:
                    Label txtDTObj1 = (Label)ctrlObj;
                    //C1WebDateEdit txtDTObj = (C1WebDateEdit)ctrlObj;
                    txtDTObj1.Text = strCtrlValue;
                    break;                
            }
        }
        return blnStatus;
    }
    private bool changeTextBoxPropertiesBasedOnSettings(ref TextBox tb, string recordOwner)
    {
        //by default password mode is set at PageCommonFunction - control init PW section
        bool showValue = false;bool showValueForOwner = false;bool showValueForAdmin = false;
        HDDatabase hddSettings = null; 
        TextBoxMode tbm = TextBoxMode.Password;
        try
        {
            hddSettings = new HDDatabase();
            DataTable dt = hddSettings.GetDataTable("select af_row_id, mem_value1 from sy_acr_mem where acr_id='3414fd6d80c5ec64'");
            if (dt!=null)
            {
                if (dt.Rows.Count>0)
                {
                    showValue = Boolean.Parse(dt.Select("af_row_id='f84a123da0c21f70'")[0]["mem_value1"].ToString());
                    showValueForOwner = Boolean.Parse(dt.Select("af_row_id='7780902c8548473c'")[0]["mem_value1"].ToString());
                    showValueForAdmin = Boolean.Parse(dt.Select("af_row_id='ac0f60691c3d909a'")[0]["mem_value1"].ToString());                    
                    if (showValue == true)
                    {
                        if (showValueForOwner == true)
                        {
                            if (HttpContext.Current.Session["user_afrowid"].ToString() == recordOwner)
                                tbm = TextBoxMode.SingleLine;
                            else
                                tbm = TextBoxMode.Password;
                        }
                        else if (showValueForAdmin == true)
                        {
                            if (HttpContext.Current.Session["user_afrowid"].ToString() == "650a333596bbf348")
                                tbm = TextBoxMode.SingleLine;
                            else
                                tbm = TextBoxMode.Password;
                        }
                        else
                        {
                            if (showValue == true)//meaningless section
                                tbm = TextBoxMode.Password;
                        }
                    }
                    tb.TextMode = tbm;
                }
            }
            
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in changeTextBoxPropertiesBasedOnSettings: " + e.Message);
        }
        finally{
            hddSettings = null;
        }
        return showValue;
    }
    private void setAjaxDate(string id, string value, ref DynamicDisplayI ddi, ref HtmlForm frmObj)
    {
        try
        {
            //string textVal = "";
            DateTime dtTextVal = new DateTime(); ;
            //Control cc = ddi.FindControl(frmObj.Controls, "ce_ajax_" + id);
            //if (cc != null)
            //{
            //    if (cc is AjaxControlToolkit.CalendarExtender)
            //    {
            //        AjaxControlToolkit.CalendarExtender ce = (AjaxControlToolkit.CalendarExtender)cc;
            //        //ce.SelectedDate = DateTime.Parse(value);
            //        DateTime dt = DateTime.Parse(value);
            //        //if (dt.Day == DateTime.Now.Day)
            //        //    ce.SelectedDate = DateTime.Parse(getDateTime4TimeZone(value));
            //             //ce.SelectedDate = new DateTime(dt.Year, dt.Month, dt.Day, 12, 59, 59);
            //    }
            //}
            Control cc = ddi.FindControl(frmObj.Controls, id);
            if (cc != null)
            {
                if (cc is TextBox)
                {
                    TextBox tb = (TextBox)cc;
                    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for locale support
                    //dtTextVal = DateTime.Parse(value, getUserCulture());
                    ////tb.Text = DateTime.Parse(value, getUserCulture()).ToString(getUserDateFormat());
                    //tb.Text = dtTextVal.ToString(getUserDateFormat());
                    ////textVal = tb.Text;
                    #endregion
                    string sLocale = HttpContext.Current.Session["userlocale"].ToString();
                    dtTextVal = DateTime.Parse(value, MBLocalization.getCultureInfo(sLocale));
                    tb.Text = MBLocalization.getLocalizedDate(sLocale, dtTextVal);
                }
            }
            cc = ddi.FindControl(frmObj.Controls, "ce_ajax_" + id);
            if (cc != null)
            {
                if (cc is AjaxControlToolkit.CalendarExtender)
                {
                    AjaxControlToolkit.CalendarExtender ce = (AjaxControlToolkit.CalendarExtender)cc;
                    //ce.SelectedDate = DateTime.Parse(value);
                    DateTime dt = DateTime.Parse(value);
                    //if (dt.Day == DateTime.Now.Day)
                        //ce.SelectedDate = DateTime.Parse(textVal);
                    ce.SelectedDate = dtTextVal;
                    //ce.SelectedDate = new DateTime(dt.Year, dt.Month, dt.Day, 12, 59, 59);
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setAjaxDate function. Error: " + e.Message);
        }
    }
    private string getDateTime4TimeZone(string value)
    {
        string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
        Localization li = new Localization();
        string ret= li.getDateTime4TimeZone(value, sUTC_Offset,false,true);
        li = null;
        return ret;
    }

    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
    //private string getUserDateFormat()
    //{
    //    Localization ll = new Localization();
    //    string ret = ll.getDateFormat();
    //    ll = null;
    //    return ret;
    //}
    #endregion

    private System.Globalization.CultureInfo getUserCulture()
    {
        #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        //Localization ll = new Localization();
        //System.Globalization.CultureInfo ret = ll.getUserCulture();
        //ll = null;
        #endregion
        System.Globalization.CultureInfo ret = MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString());
        return ret;
    }
    public string GetPageKey(DataTable dtaPageKeys, DataTable dtaPage, int intPageSeq, string strPageKeyValues)
    {
        string strKeyRet = "";
        string[] strKeys;
        string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();
        string sAF_ROW_ID = dtaPage.Rows[intPageSeq]["af_row_id"].ToString();
        string[] strPageKeys = strPageKeyValues.Split(GlobalValues.PageSetKeyChar);
        DataRow[] droCurrentPageKeys = dtaPageKeys.Select("page_id='" + sAF_ROW_ID + "'");//, "page_key_seq");
        for (int i = strPageKeys.Length - 1; i >= 0; i--)
        {
            if (strKeyRet == "")
            {
                strPageId = dtaPage.Rows[i]["page_id"].ToString();
                sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();
                strKeys = strPageKeys[i].ToString().Split(GlobalValues.PageKeyChar);
                //DataRow[] droPageKeys = dtaPageKeys.Select("page_id='" + sAF_ROW_ID + "'");//, "page_key_seq");
                DataRow[] droPageKeys = dtaPageKeys.Select("af_row_id='" + sAF_ROW_ID + "'");//, "page_key_seq");
                for (int j = 0; j < strKeys.Length; j++)
                {
                    if (droCurrentPageKeys[j]["page_key"].ToString().ToLower() == droPageKeys[j]["page_key"].ToString().ToLower())
                    {
                        if (strKeyRet != "")
                        {
                            strKeyRet += GlobalValues.PageKeyChar;
                        }
                        strKeyRet += strKeys[j];
                    }
                }
            }
        }
        return strKeyRet;
    }

    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }

    public string getMasterDetailKey(string TableName)
    {
        string sSQL = "Select af_row_id from sy_obj where object_table = '" + TableName + "'";
        HDDatabase hdd = new HDDatabase();
        string sRowId = hdd.GetColumnValue(sSQL);
        sSQL = "Select attrib_id from sy_obj_mas_detail where object_id = '" + sRowId + "'";
        string sTemp = hdd.GetColumnValue(sSQL);
        return sTemp;
    }


    private void SetDefaultValueForOwnerID(ref TextBox Text, ref HiddenField hf, string strActualCtrlId) //In add or copy mode of page default value will be set to logged in user
    {
        if (strActualCtrlId.ToLower().Contains("_owner_id"))
        {
            //AddafadminInDropDown(ref );
        }
        if (HttpContext.Current.Request.QueryString["PK"] == null)
        {
            if (strActualCtrlId.ToLower().Contains("_owner_id"))
            {
                //DDL.SelectedValue = HttpContext.Current.Session["user_afrowid"].ToString();
                Text.Text = HttpContext.Current.Session["userid"].ToString();
                hf.Value = HttpContext.Current.Session["user_afrowid"].ToString();
            }

        }

        if (HttpContext.Current.Request.QueryString["CPY"] != null)
        {
            if (strActualCtrlId.ToLower().Contains("_owner_id"))
            {
                //DDL.SelectedValue = HttpContext.Current.Session["user_afrowid"].ToString();
                Text.Text = HttpContext.Current.Session["userid"].ToString();
                hf.Value = HttpContext.Current.Session["user_afrowid"].ToString();
            }
        }


    }

    private void AddafadminInDropDown(ref DropDownList DDL)
    {
        HDDatabase HDD = new HDDatabase();
        ListItem item;
        try
        {
            if (HttpContext.Current.Session["user_afrowid"] != null)
            {
                if (HttpContext.Current.Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
                {
                    item = new ListItem(HDD.GetColumnValue("select user_id from sy_usr where af_row_id = 'e51e0327224a2eb9'"), "e51e0327224a2eb9");
                    if (!DDL.Items.Contains(item))
                    {
                        DDL.Items.Add(item);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddafadminInDropDown:" + ex.Message);
        }
        finally
        {
            HDD = null;
            item = null;
        }
    }

    public string GetUserIDFromAfrowid(string af_row_id)
    {
        string result = "";
        HDDatabase Hdd = new HDDatabase();
        try
        {
            result = Hdd.GetColumnValue("select user_id from sy_usr where af_row_id = '" + af_row_id + "'");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getUSeridFromAfrowid :" + ex.Message);
        }
        finally
        {
            Hdd = null;
        }
        return result;

    }

    public bool SetValueForDDE(ref DropDownList DDL, string strBindRowID, DataTable dtBind, string strvalue)
    {
        bool status = true;
        BindControl BC = new BindControl();
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (dtBind != null)
            {
                status = AssignValueforDDE(ref DDL, strvalue, dtBind);
            }
            else if (strBindRowID.Trim() != "")
            {
                string sql = BC.GetBindSql(strBindRowID);
                if (sql.Trim() != "")
                {
                    DataTable dt = HDD.GetDataTable(sql);
                    status = AssignValueforDDE(ref DDL, strvalue, dt);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SetValueForDDE :" + ex.Message);
            status = false;

        }
        finally
        {
            BC = null;
            HDD = null;
        }
        return status;
    }
    private bool AssignValueforDDE(ref DropDownList DDL, string strvalue, DataTable dt)
    {
        bool status = true;
        try
        {
            if (dt != null)
            {
                DataRow[] drr = dt.Select("Val='" + strvalue + "'");
                if (drr.Length > 0)
                {
                    ListItem Item = new ListItem(drr[0]["Fld"].ToString(), drr[0]["Val"].ToString());
                    if (!DDL.Items.Contains(Item))
                        DDL.Items.Insert(0, Item);

                    DDL.SelectedValue = Item.Value;
                    status = true;
                }
                else
                {
                    status = false;
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : AssignValueforDDE :"+ ex.Message);
            status = false;
        }
        return status;
    }

    private void AssignValueForDD(ref DropDownList DD,string strCtrlType,string strActualValue, string strCtrlValue)
    {
        try
        {
            if(DD!=null)
              if(DD.Items.Count>0)
                  if (strCtrlType.ToUpper() == "DA")
                  {
                      DD.SelectedValue = strActualValue;
                  }
                  else if (strCtrlType.ToUpper() == "DT")
                  {
                      DD.SelectedValue = strActualValue;
                  }
                  else
                  {
                      //DD.SelectedValue = strCtrlValue;
                      DD.Text = strCtrlValue;
                  }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : AssignValueForDD :"+ ex.Message);
        }
    }

}

